package cn.dgiot.fd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dgiot.fd.dao.IPLCWarnDAO;
import cn.dgiot.fd.model.DeviceStateModel;
import cn.dgiot.fd.model.PLCWarnModel;
import cn.dgiot.fd.service.IDeviceStateService;
import cn.dgiot.fd.service.IPLCWarnService;

/**
 * [下位机告警记录]
 * @author
 *
 */
@Service
public class PLCWarnServiceImpl implements IPLCWarnService{

	@Autowired
	private IPLCWarnDAO plcWarnDAO;

	@Autowired
	private IDeviceStateService deviceStateService;
	
	@Override
	public PLCWarnModel getPLCWarn(PLCWarnModel plcWarnModel) {
		// TODO Auto-generated method stub
		return plcWarnDAO.getPLCWarn(plcWarnModel);
	}

	@Override
	public void insertPLCWarn(PLCWarnModel plcWarnModel) {
		String deviceName = plcWarnModel.getDeviceName();
		List<PLCWarnModel> plcWarnModelList = new ArrayList<PLCWarnModel>();
		String productKey = plcWarnModel.getProductKey();
		String dpno = plcWarnModel.getDpno();
		String wtype = plcWarnModel.getWtype();
		PLCWarnModel result = plcWarnDAO.getPLCWarn(new PLCWarnModel(deviceName, productKey,dpno, wtype));
		
		PLCWarnModel param = new PLCWarnModel();
		param.setDeviceName(deviceName);
		param.setProductKey(productKey);
		param.setDpno(dpno);
		param.setWtype(plcWarnModel.getWtype());
		param.setVal(plcWarnModel.getVal());
		param.setStatus(plcWarnModel.getStatus());
		param.setCreateTime(plcWarnModel.getCreateTime());
		if(result != null) {
			plcWarnDAO.updatePLCWarnStatus(param);
		}else {
	    	DeviceStateModel deviceStateModel = new DeviceStateModel();
	    	deviceStateModel.setDeviceName(deviceName);
	    	deviceStateModel.setProductKey(plcWarnModel.getProductKey());
	    	DeviceStateModel deviceStateModelResult = deviceStateService.getDeviceState(deviceStateModel);
			param.setIotId(deviceStateModelResult.getIotId());
			param.setId(UUID.randomUUID().toString().replace("-", ""));
			plcWarnModelList.add(param);
		}
		
		if(plcWarnModelList != null && plcWarnModelList.size() > 0) {
			plcWarnDAO.insertPLCWarn(plcWarnModelList);
		}
	}

	@Override
	public void updatePLCWarnStatus(PLCWarnModel plcWarnModel) {
		// TODO Auto-generated method stub
		plcWarnDAO.updatePLCWarnStatus(plcWarnModel);
	}

}
